package com.sunyard.manage.service.impl;

import com.sunyard.dal.bo.token.TokenBO;
import com.sunyard.manage.client.AuthorizationClient;
import com.sunyard.manage.service.RefreshTokenService;
import com.sunyard.utils.Response.BaseResult;
import com.sunyard.utils.Response.GetResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author 张昊坤
 * @Description token过期刷新
 * @Date 2021/3/8 14:55
 */
@Service
@Slf4j
public class RefreshTokenServiceImpl implements RefreshTokenService {
    @Autowired
    private AuthorizationClient authrozationClient;

    @Override
    public BaseResult refreshToken(TokenBO tokenBO, HttpServletResponse response, HttpServletRequest request) {
        log.info("refreshToken");
        String token = tokenBO.getToken();
        Map<String, String> map = new HashMap<>();
        map.put("token", token);
        try {
            Map<String, String> authInfo = (Map<String, String>) authrozationClient.refreshToken(map);
            if (!"00".equals(authInfo.get("respCode"))) {
                return GetResult.getResultRelogin("获取权限失败");
            }
            if (StringUtils.isBlank(authInfo.get("transInfo"))) {
                return GetResult.getResultRelogin("获取权限失败");
            }
            token = authInfo.get("transInfo");
            response.setHeader("token", token);
            response.setHeader("Access-Control-Expose-Headers", "token");
        } catch (Exception e) {
            e.printStackTrace();
            return GetResult.getResultRelogin("获取权限失败");
        }
        return GetResult.getResult(token);
    }
}
